import { request, useUserStore, clearEmpty } from "jmash-core";
import type { AxiosPromise } from "axios";
import type {
  UserLogApi,
  UserLogPage,
  UserLogReq,
  UserLogKey,
  UserLogModel,
  UserLogExportReq,
  UserDeptJobInfoRes,
} from "./types";
import qs from "qs";
class UserLogApiImpl implements UserLogApi {
  getKey(model: UserLogModel): UserLogKey {
    return {
      logId: model.logId,
    } as UserLogKey;
  }
  /**
   * 获取安全日志分页信息
   *
   * @param queryParams 查询参数，可选，类型为 userLogQuery
   * @returns 返回请求结果
   */
  findPage(query: UserLogReq): AxiosPromise<UserLogPage> {
    query.tenant = useUserStore().user.tenant;
    clearEmpty(query);
    return request({
      url: "/v1/rbac/userLog/page",
      method: "get",
      params: query,
    });
  }

  // 查询安全日志
  findById(query: UserLogKey): AxiosPromise<UserLogModel> {
    query.tenant = useUserStore().user.tenant;
    clearEmpty(query);
    return request({
      url: "/v1/rbac/user_log/id",
      method: "get",
      params: query,
    });
  }

  /**
   * 批量删除安全日志
   *
   * @param year 年份
   * @returns 返回删除操作的结果
   */
  batchDelUserLog(year: number): AxiosPromise<number> {
    const query = {
      tenant: useUserStore().user.tenant,
      number: year,
    };
    return request({
      url: "/v1/rbac/userLog/batch",
      method: "delete",
      params: query,
    });
  }

  /**
   * 导出安全日志为Excel文件
   *
   * @param queryParams 查询参数，可选
   * @returns 返回一个Promise对象，表示请求的结果
   */
  exportExcel(queryParams: UserLogExportReq): AxiosPromise {
    clearEmpty(queryParams);
    const query = qs.stringify(queryParams, {
      arrayFormat: "brackets",
      allowDots: true,
    });
    return request({
      url:
        "/v1/rbac/userLog/" +
        useUserStore().user.tenant +
        "/userLogs.xlsx?" +
        query,
      method: "get",
      responseType: "blob",
    });
  }
}
const userLogApi = new UserLogApiImpl();
export { userLogApi };

/**
 * 用户登录日志查询
 *
 * @param userId 用户ID
 * @returns 返回请求结果
 */
export function userLogUser(userId: string, tenant?: string): AxiosPromise<UserDeptJobInfoRes> {
  const query = {
    tenant: tenant || useUserStore().user.tenant,
    userId: userId,
  };
  return request({
    url: "/v1/rbac/userLog/user",
    method: "get",
    params: query,
  });
}
